package com.example.mkio.androidpractice.Views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;

import com.example.mkio.androidpractice.R;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * Created by mk.io on 17-5-28.
 */

public class CustomView extends View {

    private static final String TAG = "CustomView";

    /**
     * 首先在 attrs.xml 文件中定义了 文本的内容、颜色、大小，所以先进行声明一下
     */
    private String mTextViewContent;

    private int mTitleSize;

    private int mTitleColor;

    /**
     * 绘制时控制文本的范围
     */
    private Rect mRect;
    private Paint mPaint;

    public CustomView(Context context) {
        this(context, null);
    }

    public CustomView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        /**
         * 获得自定义样式的样式属性
         */
        TypedArray mTypedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomView, defStyleAttr, 0);
        int n = mTypedArray.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = mTypedArray.getIndex(i);
            switch (attr) {
                case R.styleable.CustomView_titleColor:
                    mTitleColor = mTypedArray.getColor(attr, Color.RED);
                    break;
                case R.styleable.CustomView_titleText:
                    mTextViewContent = mTypedArray.getString(attr);
                    break;
                case R.styleable.CustomView_titleTextSize:
                    // 默认设置为16sp，TypeValue也可以把sp转化为px
                    mTitleSize = mTypedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
                            TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
                    break;
            }
        }
        mTypedArray.recycle();

        mPaint = new Paint();
        mPaint.setTextSize(mTitleSize);

        mRect = new Rect();
        Log.e("tetete", "999--" + mTextViewContent);
        mPaint.getTextBounds(mTextViewContent, 0, mTextViewContent.length(), mRect);
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mTextViewContent = randomText();
                postInvalidate();//调用一次 onDraw() 方法
            }
        });
    }


    /**
     * 当我们设置为WRAP_CONTENT,或者MATCH_PARENT系统帮我们测量的结果就是MATCH_PARENT的长度。所以，
     * 当设置了WRAP_CONTENT时，我们需要自己进行测量，即重写onMesure方法”：
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        Log.e(TAG, "onMeasure: " + "widthMode : " + widthMode + ",widthSize : " + widthSize + ",heightMode : " + heightMode + ",heightSize : " + heightSize);
        int realWith;
        int realHeight;
        if (widthMode == MeasureSpec.EXACTLY) {
            realWith = widthSize;
        } else {
            mPaint.setTextSize(mTitleSize);
            mPaint.getTextBounds(mTextViewContent, 0, mTextViewContent.length(), mRect);
            float textWidth = mRect.width();
            int desire = (int) (getPaddingLeft() + textWidth + getPaddingRight());
            Log.e(TAG, "onMeasure: widdth-->" + ",mTitleSize:" + mTitleSize + ",textWidth : "
                    + textWidth + ",desire:" + desire+",,,getPaddingLeft-->"+getPaddingLeft()+"getPaddingRight-->"+getPaddingRight());
            realWith = desire;
        }

        if (heightMode == MeasureSpec.EXACTLY) {
            realHeight = heightSize;
        } else {
            mPaint.setTextSize(mTitleSize);
            mPaint.getTextBounds(mTextViewContent, 0, mTextViewContent.length(), mRect);
            float textHight = mRect.height();
            int desire = (int) (getPaddingTop() + textHight + getPaddingBottom());
            Log.e(TAG, "onMeasure: height -->" + ",mTitleSize:" + mTitleSize + ",textWidth : " + textHight + ",desire:" + desire+
            "--getPaddingTop():"+getPaddingTop()+"----getPaddingBottom:"+getPaddingBottom());
            realHeight = desire;
        }
        setMeasuredDimension(realWith,realHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //cavans 绘制画布
        mPaint.setColor(Color.YELLOW);
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);


        /**
         *  绘制文字
         *
         *  需要注意点： 绘制文字 距离的计算坐标的标准为 文字的左下方  （getHeight() / 2 + mRect.height() / 2） 所以 该处为 “+” 号
         */
        mPaint.setColor(mTitleColor);
        Log.e(TAG, "onDraw: "+
                "getWidth() / 2-->"+getWidth() / 2
                +"\ngetHeight() / 2-->"+getHeight() / 2
                +"\nmRect.width() / 2--*"+mRect.width() / 2
                +"\nmRect.height() / 2---*"+mRect.height() / 2
                +"\ngetWidth() / 2 - mRect.width() / 2:===>" + (getWidth() / 2 - mRect.width() / 2)
                +"\ngetHeight() / 2 + mRect.height() / 2:###>"+(getHeight() / 2 + mRect.height() / 2));
        canvas.drawText(mTextViewContent, getWidth() / 2 - mRect.width() / 2, getHeight() / 2 + mRect.height() / 2, mPaint);
    }
    private String randomText()
    {
        Random random = new Random();
        Set<Integer> set = new HashSet<Integer>();
        while (set.size() < 4)
        {
            int randomInt = random.nextInt(10);
            set.add(randomInt);
        }
        StringBuffer sb = new StringBuffer();
        for (Integer i : set)
        {
            sb.append("" + i);
        }

        return sb.toString();
    }
}
